import { AUTH__MODAL_TITLE, AUTH_MODAL_DESC, AUTH_GET_USER_INFO_DESC } from "../constant/constant";

import { showToast } from "@/utils/util";
const ToastTitle = "获取权限";
/**
 * 权限获取校验工具
 * 封装微信小程序的权限获取校验操作
 */
const allowedPermission = {
	"userInfo": "用户信息",
	"userLocation": "地理位置",
	"address": "通信地址",
	"record": "麦克风",
	"camera": "相机",
	"writePhotosAlbum": "保存到相册",
	"invoice": "获取发票",
	"invoiceTitle": "发票抬头",
	"werun": "微信运动步数",
}

export type AuthType = keyof typeof allowedPermission;

const auth = {
	
	/**
	 * 检查权限状态
	 * @param {AuthType} authType 权限类型
	 * @returns {Promise<boolean>} 权限状态
	 */
	check(authType: AuthType): Promise<boolean> {

		const scope: `scope.${AuthType}` = `scope.${authType}`;
		return new Promise((resolve, reject) => {
			uni.getSetting({
				success(res) {
					resolve(res.authSetting[scope] ?? false);
				},
				fail(err) {
					console.error(`Get ${authType} operation failed`, err);
					resolve(false);
				}
			})
		})
	},
	
	/**
     * 请求权限
     * @param {AuthType} authType 权限类型
     * @returns {Promise<boolean>} 是否授权成功
     */
	request(authType: AuthType): Promise<boolean> {
		const scope = `scope.${authType}`;
		return new Promise((resolve, reject) => {
			uni.authorize({
				scope,
				success (res) {
				    // 用户已经同意小程序使用权限
                    showToast(ToastTitle, "success");
                    resolve(true);
				},
				fail (err) {
                    showToast(ToastTitle, "error");
                    resolve(false);
				}
			})
		})
	},
	
	/**
	 * 显示权限引导弹窗
	 * @param {AuthType} authType 权限类型
	 * @param {string} title 弹窗标签
	 * @param {string} desc 弹窗描述
	 * @returns {Promise<boolean>} 是否授权成功
	 */
	openSetting(authType: AuthType, title?: string, desc?: string): Promise<boolean> {
		const that = this;

		const t = title || AUTH__MODAL_TITLE;
		const d = desc || AUTH_MODAL_DESC;
		const authDesc = allowedPermission[authType];
		const scope = `scope.${authType}`;
		return new Promise((resolve, reject) => {
			
			uni.showModal({
				title: `${authDesc} ${t}`,
				content: d,
				confirmText: "去授权",
				complete: (res) => {
					if (res.cancel) {
						// 用户点击取消
						showToast(ToastTitle, "error");
						resolve(false);
					} else if (res.confirm) {
						// 用户点击去授权
						uni.openSetting({
							success (res) {
								that.check(authType).then(status => {
									status ? showToast(ToastTitle, "success") : showToast(ToastTitle, "error");
									resolve(status);
								})
							},
							fail (err) {
								showToast(ToastTitle, "error");
								resolve(false);
							}
						})
					}
				}
			})
		})
	},
	
	/**
	 * 获取用户信息。页面产生点击事件（例如 button 上 bindtap 的回调中）后才可调用
	 * @param {*} desc 描述信息
	 * @returns {Promise<UniApp.UserInfo | null>} 用户信息
	 */
	getUserInfo(desc: string = AUTH_GET_USER_INFO_DESC): Promise<UniApp.UserInfo | null> {
		return new Promise((resolve, reject) => {
				
			uni.getUserProfile({
				desc,
				success(res) {
					resolve(res.userInfo);
				},
				fail(err) {
					resolve(null);
				}
			})
		})
	},
	
	/**
	 * 完整的权限处理流程（检查+获取）
	 * @param {AuthType} authType 权限类型
	 * @returns {Promise<boolean>} 是否获取权限
	 */
	async ensure(authType: AuthType): Promise<boolean> {
		const that = this;
		// 检查是否有授权
		const status = await that.check(authType);
		if (status) {
			return true;
		}
		// 没有授权，弹出授权请求
		return await that.request(authType);
	},

}

export default auth;
